import Vue from "vue";
import Vuex from "vuex";
import tabBar from './tebBar.js';
import { apiUploadImage } from "@/api/index.js";
import { Toast } from "vant";

Vue.use(Vuex);

const store = new Vuex.Store({
    state: {
        userAgreement: true,
        uploadedImages: [] // 存储格式：[{ id: "img_123456_789", url: "https://xxx.com/xxx.jpg" }]
    },
    mutations: {
        CHANGE_SHOW(state, userAgreement) {
            state.userAgreement = userAgreement;
        },

        // 添加上传图片（接收{id, url}对象）
        ADD_UPLOADED_IMAGE(state, image) {
            // 防重：避免同一ID的图片重复存储
            const isDuplicate = state.uploadedImages.some(img => img.id === image.id);
            if (!isDuplicate) {
                state.uploadedImages.push(image);
                // 同步存储到localStorage
                localStorage.setItem('uploadedImages', JSON.stringify(state.uploadedImages));
            }
        },

        // 根据ID删除图片
        REMOVE_UPLOADED_IMAGE(state, imageId) {
            state.uploadedImages = state.uploadedImages.filter(img => img.id !== imageId);
            localStorage.setItem('uploadedImages', JSON.stringify(state.uploadedImages));
        },

        // 初始化：从localStorage加载（确保ID和URL存在）
        INIT_UPLOADED_IMAGES(state) {
            const savedImages = localStorage.getItem('uploadedImages');
            if (savedImages) {
                state.uploadedImages = JSON.parse(savedImages);
            }
        },

        // 清空所有图片
        CLEAR_UPLOADED_IMAGES(state) {
            state.uploadedImages = [];
            localStorage.removeItem('uploadedImages');
        }
    },
    actions: {
        // 异步上传：调用接口拿URL→生成ID→存储
        async uploadImage({ commit }, params) {
            try {
                Toast.loading({ message: "图片上传中...", forbidClick: true, duration: 0 });

                // 1. 调用接口（传递FormData，接口仅返回URL字符串）
                const imageUrl = await apiUploadImage(params.formData);
                // 防错：确保接口返回有效URL
                if (!imageUrl || typeof imageUrl !== "string") {
                    throw new Error("接口返回无效URL");
                }

                // 2. 前端自动生成唯一ID（时间戳+随机数，避免重复）
                const imageId = `img_${Date.now()}_${Math.floor(Math.random() * 1000)}`;

                // 3. 构造图片信息（id+url），存储到Vuex和localStorage
                const imageInfo = { id: imageId, url: imageUrl };
                commit("ADD_UPLOADED_IMAGE", imageInfo);

                Toast.clear();
                return imageInfo; // 返回给组件，便于后续处理
            } catch (error) {
                Toast.clear();
                console.error("Vuex 上传图片失败:", error);
                throw new Error(error.message || "图片上传失败");
            }
        },

        // 删除图片（按ID删除）
        async deleteImage({ commit }, imageId) {
            return new Promise((resolve, reject) => {
                try {
                    commit("REMOVE_UPLOADED_IMAGE", imageId);
                    resolve();
                } catch (error) {
                    console.error("Vuex 删除图片失败:", error);
                    reject(new Error("图片删除失败"));
                }
            });
        }
    },
    getters: {
        getUploadedImages: state => state.uploadedImages
    },
    modules: {
        tabBar
    },
});

export default store;